import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import { ScrollArea } from '@/components/ui/scroll-area';
import { toast } from 'sonner';
import {
  Rocket,
  Plus,
  Play,
  Pause,
  RotateCcw,
  CheckCircle,
  AlertCircle,
  Clock,
  GitBranch,
  Tag,
  Users,
  Calendar,
  Settings,
  Download,
  Upload,
  Eye,
  Edit,
  Trash2,
  TrendingUp,
  Server,
  Globe,
  RefreshCw,
  Activity,
  Shield,
  Zap,
  FileText,
  GitCommit,
  Timer,
  Target,
  X,
  Loader2
} from 'lucide-react';

/**
 * 发布状态枚举
 */
type ReleaseStatus = 'draft' | 'pending' | 'in-progress' | 'deployed' | 'failed' | 'rolled-back';

/**
 * 环境类型枚举
 */
type Environment = 'development' | 'staging' | 'production';

/**
 * 发布数据接口
 */
interface Release {
  id: string;
  version: string;
  title: string;
  description: string;
  status: ReleaseStatus;
  progress: number;
  environment: Environment;
  releaseDate: string;
  deployedAt?: string;
  author: string;
  approver?: string;
  deploymentTime: string;
  rollbackAvailable: boolean;
  changes: string[];
  commitHash?: string;
  branch: string;
  buildNumber: number;
  artifacts: {
    name: string;
    size: string;
    downloadUrl: string;
  }[];
  healthChecks: {
    name: string;
    status: 'passed' | 'failed' | 'pending';
    lastCheck: string;
  }[];
  metrics: {
    cpuUsage: number;
    memoryUsage: number;
    responseTime: number;
    errorRate: number;
  };
}

/**
 * 环境信息接口
 */
interface EnvironmentInfo {
  name: Environment;
  label: string;
  color: string;
  status: 'healthy' | 'deploying' | 'error' | 'maintenance';
  url: string;
  lastDeployment?: string;
  currentVersion?: string;
  instances: number;
  uptime: string;
}

/**
 * 部署统计接口
 */
interface DeploymentStat {
  label: string;
  value: string;
  change: string;
  trend: 'up' | 'down';
  description: string;
}

/**
 * 发布表单数据接口
 */
interface ReleaseFormData {
  version: string;
  title: string;
  description: string;
  environment: Environment;
  branch: string;
  changes: string[];
  autoRollback: boolean;
  healthCheckEnabled: boolean;
  canaryDeployment: boolean;
  canaryPercentage: number;
}

/**
 * 初始化发布数据
 */
const initializeReleases = (): Release[] => [
  {
    id: '1',
    version: 'v2.1.3',
    title: '智能聊天功能优化',
    description: '新增AI对话优化、性能提升和bug修复',
    status: 'deployed',
    progress: 100,
    environment: 'production',
    releaseDate: '2024-01-15T10:30:00Z',
    deployedAt: '2024-01-15T10:45:00Z',
    author: '张开发',
    approver: '李经理',
    deploymentTime: '15分钟',
    rollbackAvailable: true,
    branch: 'release/v2.1.3',
    buildNumber: 1523,
    commitHash: 'a1b2c3d4',
    changes: [
      '新增智能对话上下文理解',
      '优化响应速度提升30%',
      '修复已知安全漏洞',
      '更新用户界面组件'
    ],
    artifacts: [
      { name: 'frontend-v2.1.3.zip', size: '12.5MB', downloadUrl: '/api/artifacts/frontend-v2.1.3.zip' },
      { name: 'backend-v2.1.3.tar.gz', size: '8.2MB', downloadUrl: '/api/artifacts/backend-v2.1.3.tar.gz' }
    ],
    healthChecks: [
      { name: 'API健康检查', status: 'passed', lastCheck: '2024-01-15T11:00:00Z' },
      { name: '数据库连接', status: 'passed', lastCheck: '2024-01-15T11:00:00Z' },
      { name: '缓存服务', status: 'passed', lastCheck: '2024-01-15T11:00:00Z' }
    ],
    metrics: {
      cpuUsage: 45,
      memoryUsage: 62,
      responseTime: 120,
      errorRate: 0.1
    }
  },
  {
    id: '2',
    version: 'v2.1.4',
    title: '用户权限系统升级',
    description: '增强RBAC权限控制和安全性改进',
    status: 'in-progress',
    progress: 65,
    environment: 'staging',
    releaseDate: '2024-01-20T09:00:00Z',
    author: '李测试',
    deploymentTime: '预计25分钟',
    rollbackAvailable: false,
    branch: 'release/v2.1.4',
    buildNumber: 1524,
    commitHash: 'e5f6g7h8',
    changes: [
      '新增细粒度权限控制',
      '优化用户角色管理',
      '增强API安全验证',
      '添加审计日志功能'
    ],
    artifacts: [
      { name: 'frontend-v2.1.4.zip', size: '12.8MB', downloadUrl: '/api/artifacts/frontend-v2.1.4.zip' },
      { name: 'backend-v2.1.4.tar.gz', size: '8.5MB', downloadUrl: '/api/artifacts/backend-v2.1.4.tar.gz' }
    ],
    healthChecks: [
      { name: 'API健康检查', status: 'pending', lastCheck: '2024-01-20T09:30:00Z' },
      { name: '数据库连接', status: 'passed', lastCheck: '2024-01-20T09:30:00Z' },
      { name: '缓存服务', status: 'passed', lastCheck: '2024-01-20T09:30:00Z' }
    ],
    metrics: {
      cpuUsage: 52,
      memoryUsage: 68,
      responseTime: 135,
      errorRate: 0.2
    }
  },
  {
    id: '3',
    version: 'v2.2.0',
    title: '数据分析模块重构',
    description: '全新的数据可视化和分析功能',
    status: 'pending',
    progress: 0,
    environment: 'development',
    releaseDate: '2024-01-25T14:00:00Z',
    author: '王架构',
    deploymentTime: '预计40分钟',
    rollbackAvailable: false,
    branch: 'feature/analytics-v2',
    buildNumber: 1525,
    commitHash: 'i9j0k1l2',
    changes: [
      '重构数据分析引擎',
      '新增实时数据看板',
      '优化查询性能',
      '增加自定义报表功能'
    ],
    artifacts: [
      { name: 'frontend-v2.2.0.zip', size: '15.2MB', downloadUrl: '/api/artifacts/frontend-v2.2.0.zip' },
      { name: 'backend-v2.2.0.tar.gz', size: '10.1MB', downloadUrl: '/api/artifacts/backend-v2.2.0.tar.gz' }
    ],
    healthChecks: [
      { name: 'API健康检查', status: 'pending', lastCheck: '' },
      { name: '数据库连接', status: 'pending', lastCheck: '' },
      { name: '缓存服务', status: 'pending', lastCheck: '' }
    ],
    metrics: {
      cpuUsage: 0,
      memoryUsage: 0,
      responseTime: 0,
      errorRate: 0
    }
  }
];

/**
 * 初始化环境数据
 */
const initializeEnvironments = (): EnvironmentInfo[] => [
  {
    name: 'development',
    label: '开发环境',
    color: 'bg-blue-500',
    status: 'healthy',
    url: 'https://dev.example.com',
    lastDeployment: '2024-01-25T08:30:00Z',
    currentVersion: 'v2.2.0-dev',
    instances: 2,
    uptime: '99.2%'
  },
  {
    name: 'staging',
    label: '测试环境',
    color: 'bg-yellow-500',
    status: 'deploying',
    url: 'https://staging.example.com',
    lastDeployment: '2024-01-20T09:15:00Z',
    currentVersion: 'v2.1.4',
    instances: 3,
    uptime: '99.8%'
  },
  {
    name: 'production',
    label: '生产环境',
    color: 'bg-green-500',
    status: 'healthy',
    url: 'https://app.example.com',
    lastDeployment: '2024-01-15T10:45:00Z',
    currentVersion: 'v2.1.3',
    instances: 8,
    uptime: '99.9%'
  }
];

/**
 * 初始化部署统计数据
 */
const initializeDeploymentStats = (): DeploymentStat[] => [
  {
    label: '部署成功率',
    value: '98.5%',
    change: '+2.1%',
    trend: 'up',
    description: '过去30天的部署成功率'
  },
  {
    label: '平均部署时间',
    value: '12分钟',
    change: '-3分钟',
    trend: 'down',
    description: '相比上月减少了3分钟'
  },
  {
    label: '本月发布次数',
    value: '24',
    change: '+6',
    trend: 'up',
    description: '比上月增加了6次发布'
  },
  {
    label: '回滚次数',
    value: '2',
    change: '-1',
    trend: 'down',
    description: '本月回滚次数减少'
  }
];

export default function ReleaseManagement() {
  // 状态管理
  const [releases, setReleases] = useState<Release[]>(initializeReleases());
  const [environments, setEnvironments] = useState<EnvironmentInfo[]>(initializeEnvironments());
  const [deploymentStats, setDeploymentStats] = useState<DeploymentStat[]>(initializeDeploymentStats());
  const [selectedRelease, setSelectedRelease] = useState<Release | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deploymentLogs, setDeploymentLogs] = useState<string[]>([]);
  const [isDeploying, setIsDeploying] = useState<string | null>(null);
  
  // 表单数据
  const [formData, setFormData] = useState<ReleaseFormData>({
    version: '',
    title: '',
    description: '',
    environment: 'development',
    branch: 'main',
    changes: [],
    autoRollback: true,
    healthCheckEnabled: true,
    canaryDeployment: false,
    canaryPercentage: 10
  });
  
  const [newChange, setNewChange] = useState('');

  /**
   * 获取状态徽章样式
   */
  const getStatusBadge = (status: ReleaseStatus) => {
    const statusConfig = {
      'draft': { variant: 'secondary' as const, label: '草稿' },
      'pending': { variant: 'outline' as const, label: '待审批' },
      'in-progress': { variant: 'default' as const, label: '部署中' },
      'deployed': { variant: 'default' as const, label: '已部署' },
      'failed': { variant: 'destructive' as const, label: '失败' },
      'rolled-back': { variant: 'secondary' as const, label: '已回滚' }
    };
    
    const config = statusConfig[status] || statusConfig['draft'];
    return <Badge variant={config.variant}>{config.label}</Badge>;
  };

  /**
   * 获取环境状态样式
   */
  const getEnvironmentStatus = (status: string) => {
    const statusConfig = {
      'healthy': { color: 'text-green-600', icon: CheckCircle, label: '健康' },
      'deploying': { color: 'text-yellow-600', icon: Clock, label: '部署中' },
      'error': { color: 'text-red-600', icon: AlertCircle, label: '错误' },
      'maintenance': { color: 'text-gray-600', icon: Settings, label: '维护中' }
    };
    return statusConfig[status] || statusConfig['healthy'];
  };

  /**
   * 模拟API调用延迟
   */
  const simulateApiCall = (duration: number = 2000): Promise<void> => {
    return new Promise(resolve => setTimeout(resolve, duration));
  };

  /**
   * 创建新发布
   */
  const handleCreateRelease = async () => {
    if (!formData.version || !formData.title) {
      setError('版本号和标题为必填项');
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      await simulateApiCall(1500);
      
      const newRelease: Release = {
        id: Date.now().toString(),
        version: formData.version,
        title: formData.title,
        description: formData.description,
        status: 'draft',
        progress: 0,
        environment: formData.environment,
        releaseDate: new Date().toISOString(),
        author: '当前用户',
        deploymentTime: '预计20分钟',
        rollbackAvailable: false,
        branch: formData.branch,
        buildNumber: Math.floor(Math.random() * 9999) + 1000,
        commitHash: Math.random().toString(36).substring(2, 10),
        changes: formData.changes,
        artifacts: [],
        healthChecks: [
          { name: 'API健康检查', status: 'pending', lastCheck: '' },
          { name: '数据库连接', status: 'pending', lastCheck: '' },
          { name: '缓存服务', status: 'pending', lastCheck: '' }
        ],
        metrics: {
          cpuUsage: 0,
          memoryUsage: 0,
          responseTime: 0,
          errorRate: 0
        }
      };

      setReleases(prev => [newRelease, ...prev]);
      setIsCreateDialogOpen(false);
      setFormData({
        version: '',
        title: '',
        description: '',
        environment: 'development',
        branch: 'main',
        changes: [],
        autoRollback: true,
        healthCheckEnabled: true,
        canaryDeployment: false,
        canaryPercentage: 10
      });
      
      toast.success('发布创建成功！');
    } catch (err) {
      setError('创建发布失败，请重试');
      toast.error('创建发布失败');
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 部署发布
   */
  const handleDeploy = async (releaseId: string) => {
    setIsDeploying(releaseId);
    setDeploymentLogs([]);
    
    try {
      const release = releases.find(r => r.id === releaseId);
      if (!release) return;

      // 更新状态为部署中
      setReleases(prev => prev.map(r => 
        r.id === releaseId 
          ? { ...r, status: 'in-progress' as ReleaseStatus, progress: 0 }
          : r
      ));

      // 模拟部署过程
      const steps = [
        '开始部署流程...',
        '检查代码分支...',
        '构建应用程序...',
        '运行测试用例...',
        '生成部署包...',
        '上传到目标环境...',
        '启动健康检查...',
        '更新负载均衡器...',
        '部署完成！'
      ];

      for (let i = 0; i < steps.length; i++) {
        await simulateApiCall(800);
        setDeploymentLogs(prev => [...prev, `[${new Date().toLocaleTimeString()}] ${steps[i]}`]);
        
        const progress = Math.round(((i + 1) / steps.length) * 100);
        setReleases(prev => prev.map(r => 
          r.id === releaseId 
            ? { ...r, progress }
            : r
        ));
      }

      // 部署成功
      setReleases(prev => prev.map(r => 
        r.id === releaseId 
          ? { 
              ...r, 
              status: 'deployed' as ReleaseStatus, 
              progress: 100,
              deployedAt: new Date().toISOString(),
              rollbackAvailable: true,
              healthChecks: r.healthChecks.map(hc => ({
                ...hc,
                status: 'passed' as const,
                lastCheck: new Date().toISOString()
              })),
              metrics: {
                cpuUsage: Math.floor(Math.random() * 30) + 40,
                memoryUsage: Math.floor(Math.random() * 20) + 50,
                responseTime: Math.floor(Math.random() * 50) + 100,
                errorRate: Math.random() * 0.5
              }
            }
          : r
      ));

      toast.success('部署成功！');
    } catch (err) {
      setReleases(prev => prev.map(r => 
        r.id === releaseId 
          ? { ...r, status: 'failed' as ReleaseStatus }
          : r
      ));
      toast.error('部署失败');
    } finally {
      setIsDeploying(null);
    }
  };

  /**
   * 回滚发布
   */
  const handleRollback = async (releaseId: string) => {
    setIsLoading(true);
    
    try {
      await simulateApiCall(3000);
      
      setReleases(prev => prev.map(r => 
        r.id === releaseId 
          ? { ...r, status: 'rolled-back' as ReleaseStatus, rollbackAvailable: false }
          : r
      ));
      
      toast.success('回滚成功！');
    } catch (err) {
      toast.error('回滚失败');
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 删除发布
   */
  const handleDeleteRelease = async (releaseId: string) => {
    setIsLoading(true);
    
    try {
      await simulateApiCall(1000);
      setReleases(prev => prev.filter(r => r.id !== releaseId));
      if (selectedRelease?.id === releaseId) {
        setSelectedRelease(null);
      }
      toast.success('发布删除成功！');
    } catch (err) {
      toast.error('删除失败');
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 添加变更记录
   */
  const handleAddChange = () => {
    if (newChange.trim()) {
      setFormData(prev => ({
        ...prev,
        changes: [...prev.changes, newChange.trim()]
      }));
      setNewChange('');
    }
  };

  /**
   * 移除变更记录
   */
  const handleRemoveChange = (index: number) => {
    setFormData(prev => ({
      ...prev,
      changes: prev.changes.filter((_, i) => i !== index)
    }));
  };

  /**
   * 刷新数据
   */
  const handleRefresh = async () => {
    setIsLoading(true);
    try {
      await simulateApiCall(1000);
      // 这里可以重新获取最新数据
      toast.success('数据刷新成功！');
    } catch (err) {
      toast.error('刷新失败');
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 格式化时间
   */
  const formatDateTime = (dateString: string) => {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleString('zh-CN');
  };

  // 初始化选中第一个发布
  useEffect(() => {
    if (releases.length > 0 && !selectedRelease) {
      setSelectedRelease(releases[0]);
    }
  }, [releases, selectedRelease]);



  const getStatusIcon = (status: ReleaseStatus) => {
    switch (status) {
      case 'deployed':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'in-progress':
        return <Clock className="w-4 h-4 text-blue-500" />;
      case 'pending':
        return <AlertCircle className="w-4 h-4 text-yellow-500" />;
      case 'failed':
        return <AlertCircle className="w-4 h-4 text-red-500" />;
      case 'draft':
        return <FileText className="w-4 h-4 text-gray-500" />;
      case 'rolled-back':
        return <RotateCcw className="w-4 h-4 text-orange-500" />;
      default:
        return <Clock className="w-4 h-4 text-gray-500" />;
    }
  };



  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* 页面标题 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">版本发布管理</h1>
            <p className="text-gray-600 mt-1">管理系统版本发布和部署流程</p>
          </div>
          <div className="flex space-x-3">
            <Button variant="outline" size="sm">
              <Download className="w-4 h-4 mr-2" />
              导出报告
            </Button>
            <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
              <DialogTrigger asChild>
                <Button size="sm">
                  <Plus className="w-4 h-4 mr-2" />
                  创建发布
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                  <DialogHeader>
                    <DialogTitle>创建新发布</DialogTitle>
                    <DialogDescription>
                      填写发布信息以创建新的版本发布
                    </DialogDescription>
                  </DialogHeader>
                  
                  {error && (
                    <div className="bg-red-50 border border-red-200 rounded-md p-3 text-red-700 text-sm">
                      {error}
                    </div>
                  )}
                  
                  <div className="space-y-6">
                    {/* 基本信息 */}
                    <div className="space-y-4">
                      <h4 className="font-medium text-sm text-gray-900">基本信息</h4>
                      <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-2">
                          <Label htmlFor="version">版本号 *</Label>
                          <Input
                            id="version"
                            placeholder="例如: v2.1.5"
                            value={formData.version}
                            onChange={(e) => setFormData({...formData, version: e.target.value})}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="branch">代码分支</Label>
                          <Input
                            id="branch"
                            placeholder="例如: main, develop"
                            value={formData.branch}
                            onChange={(e) => setFormData({...formData, branch: e.target.value})}
                          />
                        </div>
                      </div>
                      
                      <div className="space-y-2">
                        <Label htmlFor="title">发布标题 *</Label>
                        <Input
                          id="title"
                          placeholder="简要描述此次发布"
                          value={formData.title}
                          onChange={(e) => setFormData({...formData, title: e.target.value})}
                        />
                      </div>
                      
                      <div className="space-y-2">
                        <Label htmlFor="description">发布描述</Label>
                        <Textarea
                          id="description"
                          placeholder="详细描述此次发布的内容和变更"
                          value={formData.description}
                          onChange={(e) => setFormData({...formData, description: e.target.value})}
                          rows={3}
                        />
                      </div>
                      
                      <div className="space-y-2">
                        <Label htmlFor="environment">目标环境</Label>
                        <Select value={formData.environment} onValueChange={(value: Environment) => setFormData({...formData, environment: value})}>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="development">开发环境</SelectItem>
                            <SelectItem value="staging">测试环境</SelectItem>
                            <SelectItem value="production">生产环境</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    
                    <Separator />
                    
                    {/* 变更记录 */}
                    <div className="space-y-4">
                      <h4 className="font-medium text-sm text-gray-900">变更记录</h4>
                      <div className="space-y-2">
                        <div className="flex space-x-2">
                          <Input
                            placeholder="添加变更记录..."
                            value={newChange}
                            onChange={(e) => setNewChange(e.target.value)}
                            onKeyPress={(e) => e.key === 'Enter' && handleAddChange()}
                          />
                          <Button type="button" onClick={handleAddChange} size="sm">
                            <Plus className="w-4 h-4" />
                          </Button>
                        </div>
                        
                        {formData.changes.length > 0 && (
                          <div className="space-y-2 max-h-32 overflow-y-auto">
                            {formData.changes.map((change, index) => (
                              <div key={index} className="flex items-center justify-between bg-gray-50 p-2 rounded text-sm">
                                <span>{change}</span>
                                <Button
                                  type="button"
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => handleRemoveChange(index)}
                                >
                                  <X className="w-3 h-3" />
                                </Button>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                    
                    <Separator />
                    
                    {/* 部署选项 */}
                    <div className="space-y-4">
                      <h4 className="font-medium text-sm text-gray-900">部署选项</h4>
                      <div className="space-y-3">
                        <div className="flex items-center justify-between">
                          <div className="space-y-0.5">
                            <Label htmlFor="autoRollback">自动回滚</Label>
                            <p className="text-xs text-gray-500">部署失败时自动回滚到上一版本</p>
                          </div>
                          <Switch
                            id="autoRollback"
                            checked={formData.autoRollback}
                            onCheckedChange={(checked) => setFormData({...formData, autoRollback: checked})}
                          />
                        </div>
                        
                        <div className="flex items-center justify-between">
                          <div className="space-y-0.5">
                            <Label htmlFor="healthCheck">健康检查</Label>
                            <p className="text-xs text-gray-500">部署后进行健康检查</p>
                          </div>
                          <Switch
                            id="healthCheck"
                            checked={formData.healthCheckEnabled}
                            onCheckedChange={(checked) => setFormData({...formData, healthCheckEnabled: checked})}
                          />
                        </div>
                        
                        <div className="flex items-center justify-between">
                          <div className="space-y-0.5">
                            <Label htmlFor="canary">金丝雀部署</Label>
                            <p className="text-xs text-gray-500">先部署到部分实例进行测试</p>
                          </div>
                          <Switch
                            id="canary"
                            checked={formData.canaryDeployment}
                            onCheckedChange={(checked) => setFormData({...formData, canaryDeployment: checked})}
                          />
                        </div>
                        
                        {formData.canaryDeployment && (
                          <div className="space-y-2 ml-4">
                            <Label htmlFor="canaryPercentage">金丝雀流量比例: {formData.canaryPercentage}%</Label>
                            <input
                              type="range"
                              id="canaryPercentage"
                              min="5"
                              max="50"
                              step="5"
                              value={formData.canaryPercentage}
                              onChange={(e) => setFormData({...formData, canaryPercentage: parseInt(e.target.value)})}
                              className="w-full"
                            />
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                  
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)} disabled={isLoading}>
                      取消
                    </Button>
                    <Button onClick={handleCreateRelease} disabled={isLoading}>
                      {isLoading ? (
                        <>
                          <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                          创建中...
                        </>
                      ) : (
                        '创建发布'
                      )}
                    </Button>
                  </DialogFooter>
                </DialogContent>
            </Dialog>
          </div>
        </div>

        {/* 统计数据 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {deploymentStats.map((stat, index) => (
            <Card key={index}>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-gray-600">{stat.label}</p>
                    <p className="text-2xl font-bold text-gray-900">{stat.value}</p>
                  </div>
                  <div className="flex items-center space-x-1">
                    {stat.trend === 'up' ? (
                      <TrendingUp className="w-4 h-4 text-green-500" />
                    ) : (
                      <TrendingUp className="w-4 h-4 text-green-500 rotate-180" />
                    )}
                    <span className={`text-sm font-medium ${
                      stat.trend === 'up' ? 'text-green-600' : 'text-green-600'
                    }`}>
                      {stat.change}
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* 环境状态 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg font-semibold">环境状态</CardTitle>
            <CardDescription>各个部署环境的实时状态</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {environments.map((env, index) => (
                <div key={index} className="flex items-center justify-between p-4 border rounded-lg">
                  <div className="flex items-center space-x-3">
                    <div className={`w-3 h-3 rounded-full ${env.color}`}></div>
                    <div>
                      <h4 className="font-medium">{env.label}</h4>
                      <p className="text-sm text-gray-500">{env.name}</p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    {env.status === 'healthy' && <CheckCircle className="w-4 h-4 text-green-500" />}
                    {env.status === 'deploying' && <Clock className="w-4 h-4 text-blue-500" />}
                    <Badge variant={env.status === 'healthy' ? 'default' : 'secondary'}>
                      {env.status === 'healthy' ? '正常' : '部署中'}
                    </Badge>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 发布列表 */}
          <div className="lg:col-span-2">
            <Card>
              <CardHeader>
                <CardTitle className="text-lg font-semibold">发布历史</CardTitle>
                <CardDescription>最近的版本发布记录</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {releases.map((release) => (
                    <div
                      key={release.id}
                      className={`p-4 border rounded-lg cursor-pointer transition-colors hover:bg-gray-50 ${
                        selectedRelease?.id === release.id ? 'border-blue-500 bg-blue-50' : ''
                      }`}
                      onClick={() => setSelectedRelease(release)}
                    >
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex items-center space-x-3">
                          {getStatusIcon(release.status)}
                          <div>
                            <div className="flex items-center space-x-2">
                              <h4 className="font-medium text-gray-900">{release.version}</h4>
                              <Tag className="w-4 h-4 text-gray-400" />
                            </div>
                            <p className="text-sm text-gray-600">{release.title}</p>
                          </div>
                        </div>
                        <div className="flex items-center space-x-2">
                          {getStatusBadge(release.status)}
                          <Badge variant="outline" className="text-xs">
                            {environments.find(env => env.name === release.environment)?.label}
                          </Badge>
                        </div>
                      </div>

                      {release.status === 'in-progress' && (
                        <div className="mb-3">
                          <div className="flex items-center justify-between text-sm mb-1">
                            <span className="text-gray-600">部署进度</span>
                            <span className="font-medium">{release.progress}%</span>
                          </div>
                          <Progress value={release.progress} className="h-2" />
                        </div>
                      )}

                      <div className="flex items-center justify-between text-sm text-gray-500">
                        <div className="flex items-center space-x-4">
                          <span className="flex items-center space-x-1">
                            <Users className="w-3 h-3" />
                            <span>{release.author}</span>
                          </span>
                          <span className="flex items-center space-x-1">
                            <Calendar className="w-3 h-3" />
                            <span>{release.releaseDate}</span>
                          </span>
                          <span className="flex items-center space-x-1">
                            <Clock className="w-3 h-3" />
                            <span>{release.deploymentTime}</span>
                          </span>
                        </div>
                        <div className="flex items-center space-x-2">
                          {release.status === 'in-progress' && (
                            <>
                              <Button variant="ghost" size="sm">
                                <Pause className="w-3 h-3" />
                              </Button>
                              <Button variant="ghost" size="sm">
                                <RotateCcw className="w-3 h-3" />
                              </Button>
                            </>
                          )}
                          {release.status === 'pending' && (
                            <Button variant="ghost" size="sm">
                              <Play className="w-3 h-3" />
                            </Button>
                          )}
                          {release.rollbackAvailable && (
                            <Button variant="ghost" size="sm" className="text-orange-600">
                              <RotateCcw className="w-3 h-3" />
                            </Button>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 发布详情 */}
          <div className="lg:col-span-1">
            <div className="space-y-4">
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg font-semibold">发布详情</CardTitle>
                  <CardDescription>{selectedRelease?.version}</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <h4 className="font-medium mb-2">基本信息</h4>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-gray-600">版本号:</span>
                        <span className="font-medium">{selectedRelease?.version}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">状态:</span>
                        {selectedRelease && getStatusBadge(selectedRelease.status)}
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">环境:</span>
                        <span className="font-medium">
                          {environments.find(env => env.name === selectedRelease?.environment)?.label}
                        </span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">发布人:</span>
                        <span className="font-medium">{selectedRelease?.author}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">发布时间:</span>
                        <span className="font-medium">{selectedRelease?.releaseDate}</span>
                      </div>
                    </div>
                  </div>

                  <div>
                    <h4 className="font-medium mb-2">变更内容</h4>
                    <ul className="space-y-1 text-sm">
                      {selectedRelease?.changes.map((change, index) => (
                        <li key={index} className="flex items-start space-x-2">
                          <div className="w-1 h-1 bg-gray-400 rounded-full mt-2 flex-shrink-0"></div>
                          <span className="text-gray-600">{change}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-lg font-semibold">操作面板</CardTitle>
                </CardHeader>
                <CardContent className="space-y-2">
                  <Button variant="outline" className="w-full justify-start">
                    <Eye className="w-4 h-4 mr-2" />
                    查看详细日志
                  </Button>
                  <Button variant="outline" className="w-full justify-start">
                    <Download className="w-4 h-4 mr-2" />
                    下载发布包
                  </Button>
                  <Button variant="outline" className="w-full justify-start">
                    <Edit className="w-4 h-4 mr-2" />
                    编辑发布信息
                  </Button>
                  {selectedRelease?.rollbackAvailable && (
                    <AlertDialog>
                      <AlertDialogTrigger asChild>
                        <Button variant="outline" className="w-full justify-start text-orange-600 hover:text-orange-700">
                          <RotateCcw className="w-4 h-4 mr-2" />
                          回滚版本
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>确认回滚</AlertDialogTitle>
                          <AlertDialogDescription>
                            确定要回滚版本 {selectedRelease?.version} 吗？此操作将恢复到上一个稳定版本。
                          </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>取消</AlertDialogCancel>
                          <AlertDialogAction 
                            onClick={() => selectedRelease && handleRollback(selectedRelease.id)}
                            className="bg-orange-600 hover:bg-orange-700"
                          >
                            确认回滚
                          </AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  )}
                  
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <Button variant="outline" className="w-full justify-start text-red-600 hover:text-red-700">
                        <Trash2 className="w-4 h-4 mr-2" />
                        删除发布
                      </Button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>确认删除</AlertDialogTitle>
                        <AlertDialogDescription>
                          确定要删除版本 {selectedRelease?.version} 吗？此操作不可撤销。
                        </AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel>取消</AlertDialogCancel>
                        <AlertDialogAction 
                          onClick={() => selectedRelease && handleDeleteRelease(selectedRelease.id)}
                          className="bg-red-600 hover:bg-red-700"
                        >
                          确认删除
                        </AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-lg font-semibold">部署配置</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">灰度发布:</span>
                    <Badge variant="secondary">20%</Badge>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">自动回滚:</span>
                    <Badge variant="default">启用</Badge>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">健康检查:</span>
                    <Badge variant="default">通过</Badge>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">负载均衡:</span>
                    <Badge variant="default">正常</Badge>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}